# _*_ coding:utf-8 _*_
# @Time :2020/11/27 19:53
# @Author :yanxia
import datetime

from dateutil.relativedelta import relativedelta
from sqlalchemy import func

from application import db
from application.models.models import Bugcalculate


def qulity_data():
    """
    查询截止当前系统日期时，上一个月的项目总和、bug密度标准值、引入错误率标准值。
    :return:
     sql ="select ROUND(sum(bugdensity)/count(proname),2)," \
          "ROUND(sum(fristleak)/count(proname),2)," \
          "ROUND(sum(bringerror)/count(proname),2)," \
          "left(date_add(now(),interval-1 month),7)as datatime," \
          "count(*)as zong " \
          "from bugcalculate " \
          "where date_format(addtime,'%Y-%m') < date_format(CURDATE( ),'%Y-%m')"
    """
    today = datetime.date.today().strftime('%Y-%m-%d')
    last_year = (datetime.date.today() - relativedelta(months=+12)).strftime('%Y-%m-%d')

    result = db.session.query(
        func.ROUND(func.SUM(Bugcalculate.bugdensity) / func.count(Bugcalculate.proname), 2).label("bug_density"),
        func.ROUND(func.SUM(Bugcalculate.fristleak) / func.count(Bugcalculate.proname), 2).label("frist_misstest"),
        func.ROUND(func.SUM(Bugcalculate.bringerror) / func.count(Bugcalculate.proname), 2).label("error_Introduce"),
        func.count(Bugcalculate.id).label("total")).filter(
        Bugcalculate.addtime >= last_year, Bugcalculate.addtime <= today).all()
    data = {}
    for item in result:
        data["bugmid"] = item.bug_density
        data["introerror"] = item.error_Introduce
        data["frist_misstest"] = item.frist_misstest
        data["datatime"] = last_year
        data["total"] = item.total
    return data
